<template>
  <el-popover placement="bottom" width="400" trigger="click">
    <div>
      <el-input v-model="searchText" placeholder="搜索图标" clearable @input="handleChange"></el-input>
      <div class="iconBox">
        <span
          v-for="item in gridData"
          :key="item"
          class="iconItem"
          :class="{
            activeItem: item === icon
          }"
          @click="handleClick(item)"
        >
          <template v-if="item.includes('el-icon')">
            <i :class="item" class="elIcon" />
          </template>
          <template v-else>
            <svg-icon :icon-class="item" />
          </template>
        </span>
      </div>
    </div>
    <span slot="reference">
      <el-input ref="elInput" v-model="icon" clearable @clear="$emit('change', '')" @focus="$refs.elInput.blur()">
        <template slot="append">
          <template v-if="icon.includes('el-icon')">
            <i :class="icon" />
          </template>
          <template v-else>
            <svg-icon :icon-class="icon" />
          </template>
        </template>
      </el-input>
    </span>
  </el-popover>
</template>
<script>
import { iconList } from './icon'
export default {
  name: 'IconChoose',
  props: {
    defaultValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      searchText: '',
      icon: '',
      gridData: []
    }
  },
  created() {
    this.gridData = iconList
    this.icon = this.defaultValue ?? ''
  },
  methods: {
    handleClick(item) {
      this.icon = item
      this.$emit('change', item)
    },
    handleChange(val) {
      let list = []
      if (val) {
        iconList.forEach((item) => {
          if (item.indexOf(val) !== -1) {
            list.push(item)
          }
        })
        this.gridData = list
      } else {
        this.gridData = iconList
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.el-input-group__append {
  padding: 0 10px;
}
.iconBox {
  height: 200px;
  margin-top: 10px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;
  .iconItem {
    padding: 5px;
    font-size: 20px;
    border: 1px solid #ddd;
    margin: 5px;
    height: 40px;
    .elIcon {
      width: 1.2em;
      height: 1.2em;
      text-align: center;
    }
  }
  .iconItem:hover {
    border: 1px solid #007aff;
  }
  .activeItem {
    border: 1px solid #007aff;
  }
}
</style>
